package com.gzc.just.play.last.war.centralserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.centralserver.service.ServerStatusService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 服务器状态处理器
 * 处理服务器状态查询相关的消息
 */
@Component("central-serverStatusHandler")
public class ServerStatusHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(ServerStatusHandler.class);
    
    @Autowired
    private ServerStatusService serverStatusService;
    
    private static final int SERVER_STATUS = 3001;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 获取服务器状态
        Map<String, Object> serverStatus = serverStatusService.getServerStatus();
        
        // 发送服务器状态响应
        sendServerStatusResponse(ctx, serverStatus, true, "Server status retrieved successfully");
        
        logger.info("Client requested central server status");
    }
    
    private void sendServerStatusResponse(ChannelHandlerContext ctx, Map<String, Object> serverStatus, 
                                        boolean success, String message) {
        // 实际实现中应构造响应消息并发送给客户端
        logger.info("Sending server status response: success={}, message={}", success, message);
        
        // 简化实现：打印服务器状态内容
        if (success && serverStatus != null) {
            logger.debug("Server status content:");
            for (Map.Entry<String, Object> entry : serverStatus.entrySet()) {
                logger.debug("{}: {}", entry.getKey(), entry.getValue());
            }
        }
    }
    
    @Override
    public int getMessageId() {
        return SERVER_STATUS;
    }
    
    @Override
    public String getName() {
        return "ServerStatusHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}